import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

# Load two images
img1 = cv.imread('image.jpg')
img2 = cv.imread('mask.jpg')
plt.subplot(241), plt.imshow(img1[..., ::-1]), plt.title('img1')
plt.subplot(242), plt.imshow(img2[..., ::-1]), plt.title('img2')

# 把logo放在左上角，所以先定义ROI
rows, cols, channels = img2.shape
roi = img1[0:rows, 0:cols]
# 现在创建一个logo的mask，并创建其反向mask
img2gray = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
ret, mask = cv.threshold(img2gray, 10, 255, cv.THRESH_BINARY) # THRESH_BINARY二值化
mask_inv = cv.bitwise_not(mask)  # logo部分为0，其他为1
# 现在将ROI中的logo区域涂上黑色
img1_bg = cv.bitwise_and(roi, roi, mask=mask_inv)  # if mask(i)≠0: img1_bg(i)=src1(i) AND src2(I); else  img1_bg(i)=0
# 仅取logo图像中logo区域的部分。
img2_fg = cv.bitwise_and(img2, img2, mask=mask)
# 将logo放入ROI并修改主图像
destination = cv.add(img1_bg, img2_fg)
img1[0:rows, 0:cols] = destination
plt.subplot(243), plt.imshow(mask, 'gray'), plt.title('mask')
plt.subplot(244), plt.imshow(mask_inv, 'gray'), plt.title('mask_inv')
plt.subplot(245), plt.imshow(img1_bg[..., ::-1]), plt.title('img1_bg')
plt.subplot(246), plt.imshow(img2_fg[..., ::-1]), plt.title('img2_fg')
plt.subplot(247), plt.imshow(destination[..., ::-1]), plt.title('img1_bg + img2_fg')
plt.subplot(248), plt.imshow(img1[..., ::-1]), plt.title('img1')
plt.show()